package com.pet.shop.intercepters;

import com.alibaba.fastjson.JSONObject;
import com.pet.config.SessionConstants;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
public class WebLoginInterceptor implements HandlerInterceptor {

    private static final Logger logger = Logger.getLogger(WebLoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute(SessionConstants.USER_SESSION_KEY);
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/web/login");
            return false;
        }
        return true;
    }

    private void write(HttpServletResponse response, Map<String, Object> map) {
        //
        try {
            response.setContentType("application/json; charset=UTF-8");
            String json = JSONObject.toJSONString(map);
            response.getWriter().print(json);
        } catch (Exception ex) {
            // ignore
        }
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
